package com.crealth.handler;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crealth.Config;
import com.crealth.ConstantDefine;
import com.crealth.db.CdrDb;
import com.crealth.db.ClienteleDb;
import com.crealth.db.MyselfClienteleDb;
import com.crealth.db.UserDb;
import com.crealth.manager.ClienteleInfoManager;
import com.crealth.memcached.CdrCached;
import com.crealth.memcached.UserCached;
import com.crealth.model.CdrModel;
import com.crealth.model.UserModel;
import com.crealth.msg.NetMessageData;
import com.crealth.utils.PhoneNumDecode;

public class CdrHandler {
	private static Logger errorLog = Logger.getLogger("error_log");
	
	public static NetMessageData callingPhone(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		if (userID <= 0) {
			return null;
		}
		String callee = msgJson.getString("callee");
		if (callee == null || callee.length() < 10) {
			return null;
		}
		if (callee.startsWith("0")) {
			callee = callee.substring(1);
		}
		long cdrID = msgJson.getLongValue("cdrID");
		if (cdrID <= 0) {
			Long exitID = CdrDb.selectUserCdrExit(userID, callee);
			if (exitID == null || exitID == 0) {
				CdrModel cdrModel = new CdrModel();
				cdrModel.setCallee(callee);
				cdrModel.setUserID(userID);
				cdrModel.setHoldTm(-1);
				CdrDb.insertCdr(cdrModel);
				cdrID = cdrModel.getId();
			}
		}
		
		//MybatisManager.clienteleMapper.updateCallClientele(callee, userID);
		//MybatisManager.commit();
		
		resJson.put("cdrID", cdrID);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData beginCall(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");		
		String callee = msgJson.getString("callee");
		if (callee == null || callee.length() < 8) {
			return null;
		}
		if (callee.startsWith("0")) {
			callee = callee.substring(1);
		}
		long cdrID = msgJson.getLongValue("cdrID");
		CdrModel cdrModel = new CdrModel();
		if (msgJson.containsKey("dialType")) {
			cdrModel.setDialType(msgJson.getString("dialType"));
		}
		if (cdrID <= 0) {			
			cdrModel.setCallee(callee);
			cdrModel.setUserID(userID);
			CdrDb.insertCdr(cdrModel);
			cdrID = cdrModel.getId();
		}
		else {
			cdrModel.setId(cdrID);
			cdrModel.setHoldTm(0);
			CdrDb.updateCdrCallendByID(cdrModel);
		}
		
		if (Config.mobiPhoneEncrypt) {
			callee = PhoneNumDecode.encryptPhone(callee);
		}
		
		UserModel user = UserCached.selectUserByID(userID);
		int companyID = user.getBelongCompanyID();
		Boolean groupCall = ClienteleInfoManager.getCompanyGroupcallType(companyID);
		if (groupCall) {
			ClienteleDb.updateCdridByMobiPhone(callee, cdrID);
			ClienteleDb.updateAccCallNumByPhonenum(callee);
		}	
		ClienteleDb.updateCallClientele(callee, userID);
		MyselfClienteleDb.updateCallRecordByMobi(userID, callee, cdrID);
		
		resJson.put("cdrID", cdrID);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData endCall(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");
		long cdrID = msgJson.getLongValue("cdrID");
		String callee = msgJson.getString("callee");
		int holdTm = msgJson.getIntValue("holdTm");
		//if (cdrID <= 0 && holdTm <= 0) {
			//errorLog.error("endCall cdrID  0");
			//return null;
		//}		
		if (callee == null || callee.length() < 5) {
			errorLog.error("endCall callee  length not enough!");
			return null;
		}
		if (callee.startsWith("0")) {
			callee = callee.substring(1);
		}
		String endreason = msgJson.getString("endreason");
		String recordName = msgJson.getString("recordName");
		int ringTm = -2;
		if (msgJson.containsKey("ringTm")) {
			ringTm = msgJson.getIntValue("ringTm");
		}
		CdrModel cdrModel = new CdrModel();		
		cdrModel.setUserID(userID);
		cdrModel.setCallee(callee);
		cdrModel.setHoldTm(holdTm);
		cdrModel.setRingingTime(ringTm);
		cdrModel.setEndreason(endreason);
		cdrModel.setRecordName(recordName);
		if (cdrID > 0) {
			cdrModel.setId(cdrID);
			CdrDb.updateCdrCallendByID(cdrModel);
		}
		else {			
			CdrDb.insertCdr(cdrModel);
		}
		if (Config.mobiPhoneEncrypt) {
			callee = PhoneNumDecode.encryptPhone(callee);
		}
		
		UserModel user = UserCached.selectUserByID(userID);
		int companyID = user.getBelongCompanyID();
		Boolean groupCall = ClienteleInfoManager.getCompanyGroupcallType(companyID);
		if (groupCall && holdTm > 0) {
			ClienteleDb.updateCdridByMobiPhone(callee, cdrID);
		}
		CdrCached.addUserCdr(userID, callee);
		MyselfClienteleDb.updateCallRecordByMobi(userID, callee, cdrID);
		
		resJson.put("resCode", 0);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData searchRecordCdr(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		int userID = msgJson.getIntValue("id");		
		UserModel user = UserCached.selectUserByID(userID);
		if (user.getPosition() < ConstantDefine.Group_Leader) {			
			resJson.put("resCode", ErrorCode.ERROR_Limited_Auth);
			sendMsg.setMsgBody(resJson.toJSONString());			
			return sendMsg;
		}
		
		StringBuilder strSqlBuilder = new StringBuilder("");
		int seaUserID = 0;
		if (msgJson.containsKey("seaUserID")) {
			seaUserID = msgJson.getIntValue("seaUserID");
			strSqlBuilder.append("`user_id`=" + seaUserID);
		} 
		else {
			int userPos = user.getPosition();
			List<UserModel> underlings = null;
			int seaTeamID = 0;
			if (msgJson.containsKey("seaTeamID")) {
				seaTeamID = msgJson.getIntValue("seaTeamID");
				underlings = UserDb.selectTeamUserByTeamID(seaTeamID);
			}
			else if (msgJson.containsKey("seaCompanyID")) {
				int seaCompanyID = msgJson.getIntValue("seaCompanyID");
				underlings = UserDb.selectBranchUser(seaCompanyID);
			}
			else if (userPos >= ConstantDefine.Head_Manager) {
				underlings = UserDb.selectAllUser();
			} else if ( userPos == ConstantDefine.Group_Leader ) {
				underlings = UserDb.selectGroupUsers(user.getUserName());
				underlings.add(user);
			} else {
				underlings = UserDb.selectUnderling(userID);
			}
			
			if (underlings != null && underlings.size() > 0) {
				strSqlBuilder.append("`user_id` IN (");
				for (int idx = 0; idx < underlings.size(); ++idx) {
					UserModel umodel = underlings.get(idx);
					if (idx == 0) {
						strSqlBuilder.append(umodel.getId());
					} else {
						strSqlBuilder.append(", "+umodel.getId());
					}
				}
				strSqlBuilder.append(")");
			} else {
				strSqlBuilder.append("`user_id` > 0");
			}			
		}
		long seaTm = 0;
		if (msgJson.containsKey("seaTm")) {
			seaTm = msgJson.getLongValue("seaTm");
			Date date = new Date(seaTm*1000);       
			String strSeatm = new SimpleDateFormat("yyyy-MM-dd").format(date);
			strSeatm += " %";
			strSqlBuilder.append(" AND `call_time` LIKE '" + strSeatm + "'");			
		}
		String seaPhoneNum = "";
		if (msgJson.containsKey("seaNum")) {
			seaPhoneNum = msgJson.getString("seaNum");
			seaPhoneNum = seaPhoneNum.trim();
			if (seaPhoneNum.length() > 0 && seaPhoneNum.length() < 11) {
				strSqlBuilder.append(" AND `callee` LIKE '%" + seaPhoneNum + "%'");
			} else if (seaPhoneNum.length() == 11) {
				strSqlBuilder.append(" AND `callee`='" + seaPhoneNum + "'");
			}
		}
		int holdtm = 1;
		if (msgJson.containsKey("holdtm")) {
			holdtm = msgJson.getIntValue("holdtm");
			if (holdtm == 0) {
				strSqlBuilder.append(" AND `hold_tm` >= 30 AND 60 >= `hold_tm`");
			} else if (holdtm == 1) {
				strSqlBuilder.append(" AND `hold_tm` >= 60 AND 120 >= `hold_tm`");
			} else if (holdtm == 2) {
				strSqlBuilder.append(" AND `hold_tm` >= 120 AND 180 >= `hold_tm`");
			} else if (holdtm == 3) {
				strSqlBuilder.append(" AND `hold_tm` >= 180 AND 240 >= `hold_tm`");
			} else if (holdtm == 4) {
				strSqlBuilder.append(" AND `hold_tm` >= 240 AND 300 >= `hold_tm`");
			} else if (holdtm == 5) {
				strSqlBuilder.append(" AND `hold_tm` >= 300");
			}
		} else {
			strSqlBuilder.append(" AND `hold_tm` >= 1");
		}
		
		String strSql = strSqlBuilder.toString();
		if (strSql.length() == 0) {
			errorLog.error("strSql is null");
			return null;
		}
		List<CdrModel> cdrls = CdrDb.selectRecordCdr(seaTm, strSql, seaPhoneNum);
		int cdrNum = 0;
		if (cdrls == null || cdrls.size() == 0) {
			resJson.put("resCode", 0);
			resJson.put("cdrNum", cdrNum);
			sendMsg.setMsgBody(resJson.toJSONString());
			return sendMsg;
		}
		
		cdrNum = cdrls.size();
		JSONArray jsonArray = new JSONArray();
		for (CdrModel cdr : cdrls) {
			jsonArray.add(cdr.toJSONObject());
		}
		resJson.put("cdrls", jsonArray);
		resJson.put("cdrNum", cdrNum);
		resJson.put("resCode", 0);		
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	public static NetMessageData searchGroupCallExist(NetMessageData revData) {
		NetMessageData sendMsg = new NetMessageData();
		JSONObject resJson = new JSONObject();
		JSONObject msgJson = revData.getRevDataMsgJson();
		String callee = msgJson.getString("callee");
		if (callee == null || callee.length() < 8) {
			return null;
		}
		int userID = msgJson.getIntValue("id");
		UserModel user = UserCached.selectUserByID(userID);
		int companyID = user.getBelongCompanyID();
		Boolean groupCall = ClienteleInfoManager.getCompanyGroupcallType(companyID);
		if (!groupCall) {
			return null;
		}
		
		Timestamp uploadTm = UserDb.selectUploadGroupCallTm();
		Integer existNum = CdrDb.selectCdrByPhoneAndTm(callee, uploadTm);
		resJson.put("existNum", existNum);
		resJson.put("callee", callee);
		sendMsg.setMsgBody(resJson.toJSONString());
		return sendMsg;
	}
	
	
}
